package cn.cas.mango.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GetArea {
  private static final Set<String> allArea = new HashSet<>();
  private static final Set<String> allProvinces = new HashSet<>();
  static {
    try (BufferedReader br = new BufferedReader(new FileReader("area.txt"))) {
      String line;
      while ((line = br.readLine()) != null) {
        allArea.add(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    try (BufferedReader br = new BufferedReader(new FileReader("province.txt"))) {
      String line;
      while ((line = br.readLine()) != null) {
        allProvinces.add(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static List<String> getArea(String text) {
    Set<String> ret = new HashSet<>();
    if (text != null) {
      for (String area: allArea) {
        if (text.contains(area)) {
          ret.add(area);
          if (allProvinces.contains(area)) {
            ret.add("中国");
          }
        }
      }
    }


    return new ArrayList<>(ret);
  }

  /**
   *
   * @param text, 比对的内容
   * @return 占比最高的省市
   */
  public static String getOneArea(String text) {
    if (text == null) {
      return "未知";
    }
    List<Pair<Integer, String>> list = new ArrayList<>();
    for (String area: allArea) {
      Integer times = StringUtil.getOccurrence(text, area);
      if (times != 0) {
        list.add(new Pair<>(times, area));
      }
    }
    if (list.isEmpty()) {
      return "未知";
    }
    list.sort((a,b)->{
      if (a.getKey().equals(b.getKey())) {
        return a.getValue().compareTo(b.getValue());
      }
      return -a.getKey().compareTo(b.getKey());
    });
    String area = list.get(0).getValue();
    if (allProvinces.contains(area)) {
      return "中国";
    }
    return area;
  }

  public static Set<String> getProvince() {
    return allProvinces;
  }

}
